<?php

namespace app\common\model\user;

use app\common\model\BaseModel;
use app\common\enum\user\grade\log\ChangeType as ChangeTypeEnum;

/**
 * 用户会员等级变更记录模型
 * Class GradeLog
 * @package app\common\model\user
 */
class GradeLog extends BaseModel
{
    protected $name = 'user_grade_log';
    protected $updateTime = false;

    /**
     * 新增变更记录 (批量)
     * @param $data
     * @return array|false
     * @throws \Exception
     */
    public function records($data)
    {
        $saveData = [];
        foreach ($data as $item) {
            $saveData[] = array_merge([
                'change_type' => ChangeTypeEnum::ADMIN_USER,
                'wxapp_id' => static::$wxapp_id
            ], $item);
        }
        return $this->isUpdate(false)->saveAll($saveData);
    }
    /**
     * 计算上级添加团队数量
     * */
    public function superior($logData){
        foreach ($logData as $v){
            $s_referee_id = model('user')->where('user_id',$v['user_id'])->value('referee_id');
            if($s_referee_id != 0){
                $this->superior1($s_referee_id,$v['new_grade_id']);
            }
        }

    }
    public function superior1($s_referee_id,$new_grade_id){
        if($s_referee_id != 0){
            $num_1 = '';
            $num_2 = '';
            if($new_grade_id == 1){
                $num_1 = 'first_num';
                $num_2 = '';
            }
            if($new_grade_id  == 2){
                $num_1 = 'second_num';
                $num_2 = 'first_num';
            }
            if($new_grade_id  == 3){
                $num_1 = 'third_num';
                $num_2 = 'second_num';
            }
            if($new_grade_id  == 4){
                $num_1 = 'four_num';
                $num_2 = 'third_num';
            }
            if($new_grade_id  == 5){
                $num_1 = 'five_num';
                $num_2 = 'four_num';
            }
            if($new_grade_id  == 6){
                $num_1 = 'six_num';
                $num_2 = 'five_num';
            }
            if($new_grade_id  == 7){
                $num_1 = 'seven_num';
                $num_2 = 'six_num';
            }
            if($num_1){
                model('user')->where('user_id',$s_referee_id)->setInc($num_1,1);
            }
            if($num_2){
                $data = model('user')->where('user_id',$s_referee_id)->value($num_2);
                if($data != 0 && $data > 0){
                    model('user')->where('user_id',$s_referee_id)->setDec($num_2,1);
                }
            }
            $referee_id = model('user')->where('user_id',$s_referee_id)->value('referee_id');
            $this->superior1($referee_id,$new_grade_id);
        }
    }
}